/**   
* @Title: AppNewsServiceImpl.java 
* @Package com.zjdiepu.www.biz.zpp 
* @author zhangpp
* @date 2017年5月31日 下午2:14:22 
* @version V1.0   
*/
package com.zjdiepu.www.biz.zpp;

import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.PushPayload;

import com.google.gson.Gson;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.status.MessageStatus;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.commpent.helper.UserMapSalermanHelper;
import com.zjdiepu.www.dao.other.OtherMessageAppMapper;
import com.zjdiepu.www.dao.other.OtherMessageHandleMapper;
import com.zjdiepu.www.dao.third.BaseShortMessageMapper;
import com.zjdiepu.www.ibiz.base.ISysUserService;
import com.zjdiepu.www.ibiz.zpp.AppNewsService;
import com.zjdiepu.www.model.base.dto.SysUser;
import com.zjdiepu.www.model.other.dto.OtherMessageApp;
import com.zjdiepu.www.model.other.dto.OtherMessageHandle;
import com.zjdiepu.www.model.third.dto.BaseShortMessage;
import com.zjdiepu.www.model.zpp.news.vo.ShortMessageResult;
import com.zjdiepu.www.model.zpp.pub.ext.JpushExt;
import com.zjdiepu.www.model.zpp.pub.ext.ParamsExt;
import com.zjdiepu.www.util.CommonApiUtil;
import com.zjdiepu.www.util.PayloadBuild;

/**      
 * 项目名称：diepu-parent-biz   
 * 类名称：AppNewsServiceImpl   
 * 类描述：   
 * 创建人：zhangpp
 * 创建时间：2017年5月31日 下午2:14:22   
 * 修改人：zhangpp
 * 修改时间：2017年5月31日 下午2:14:22   
 * 修改备注：   
 * @version V1.0     
 */
@Service
public class AppNewsServiceImpl implements AppNewsService
{

	private static final Logger logger = LoggerFactory.getLogger(AppNewsServiceImpl.class);
	
	@Autowired
	private OtherMessageAppMapper otherMessageAppMapper;
	
	@Autowired
	private OtherMessageHandleMapper otherMessageHandleMapper;
	
	@Autowired
	private BaseShortMessageMapper baseShortMessageMapper;
	
	@Autowired
	private ISysUserService isysUserService;
	
	@Autowired
    private UserMapSalermanHelper userMapSalermanHelper;
	
	
	
	/* 
	* @author zhangpp
	* <p>Title: saveAPPNews</p> 
	* <p>Description: </p> 
	* @param otherMessageApp
	* @param paramsExt
	* @param currentUser 
	* @see com.zjdiepu.www.ibiz.zpp.AppNewsService#saveAPPNews(com.zjdiepu.www.model.other.dto.OtherMessageApp, com.zjdiepu.www.model.zpp.pub.ext.ParamsExt, com.zjdiepu.www.base.core.AbstractSysUser) 
	* @version V1.0
	*/
	@Override
	public void saveAPPNews(OtherMessageApp otherMessageApp,ParamsExt paramsExt, AbstractSysUser currentUser)throws Exception 
	{
		
		
		//登录人信息
		String userId = currentUser == null ? null : currentUser.getId();
		String creatorName = currentUser == null ? null : currentUser.getName();
		
		//添加 other_Message_app 表 
		//是否需要短信处理
		OtherMessageHandle otherMessageHandle = new OtherMessageHandle();
		otherMessageHandle.setTypeMsgEvent(otherMessageApp.getTypeMsgEvent());
		OtherMessageHandle result = otherMessageHandleMapper.selectRefined(otherMessageHandle);
		if(null != result && "01".equals(result.getStatusMsgHandle())) 
		{
			//01 发送短信 99 不发送短信
			if(null == paramsExt.getMobile() || ("").equals(paramsExt.getMobile()))
			{
				paramsExt.setMobile("15158822934");
			}
			int error_code = diepuFaSongDuanXin(paramsExt.getMobile(),otherMessageApp.getRemarks(),"");
			BaseShortMessage baseShortMessage = new BaseShortMessage();
			baseShortMessage.initInsertData(userId, creatorName);
			baseShortMessage.setPhone(paramsExt.getMobile());
			baseShortMessage.setPhoneCode(0);
			baseShortMessage.setFlag(error_code);
			baseShortMessage.setMessage("信用信息提交");
			baseShortMessageMapper.insert(baseShortMessage);
		}
		
		String msgId = "";
		
		//推送消息
		Set<String> alias = userMapSalermanHelper.getSalermanSysUserBySalesmanId(paramsExt.getSalesmanId());
		if(CollectionUtils.isNotEmpty(alias)) 
		{
			for(String alia : alias) 
			{
				SysUser sysUser = isysUserService.getLoginedUser(alia);
				
				if(null != sysUser && !("").equals(sysUser))
				{
					if(StringUtils.isNoneBlank(sysUser.getDeviceType()))
					{
						String devicetoken = sysUser.getDevicetoken();
						
						if(sysUser.getDeviceType().equals("ios"))
						{
							if(StringUtils.isNoneBlank(devicetoken))
							{
								try 
								{
									JPushClient client = new JPushClient(PayloadBuild.appKeyIos, PayloadBuild.masterSecretIos);
									PushPayload payload = PayloadBuild.buildIOSPayload("",devicetoken,otherMessageApp.getNotificationBar());
									PushResult push = client.sendPush(payload);	
									if(push.getResponseCode() == 200)
									{
										logger.debug("推送成功");
									}
									else
									{
										logger.error("推送失败"+push.getResponseCode());
									}
									
									msgId = String.valueOf(push.msg_id);
								} 
								catch (Exception e) 
								{
									
									logger.equals(e.getMessage());
								}
							}
						}
						else
						{
							if(StringUtils.isNotBlank(devicetoken))
							{
								try 
								{
									JPushClient client = new JPushClient(PayloadBuild.masterSecretAndorid, PayloadBuild.appKeyAndorid);
									PushPayload payload = PayloadBuild.buildAndroidWinphonePayload("", devicetoken, otherMessageApp.getNotificationBar(), "碟普科技");
									PushResult push = client.sendPush(payload);	
									if(push.getResponseCode() == 200)
									{
										logger.debug("推送成功");
									}
									else
									{
										logger.error("推送失败"+push.getResponseCode());
									}
									
									msgId = String.valueOf(push.msg_id);
								} 
								catch (Exception e) 
								{
									
									logger.equals(e.getMessage());
								}
							}
						}
					}
				}
			}
		}
		
		//删除老的未发送的消息
		OtherMessageApp otherMessageAppOld = new OtherMessageApp();
		otherMessageAppOld.setDpStatus(DpStatus.NORMAL.getCode());
		otherMessageAppOld.setBusiId(otherMessageApp.getBusiId());
		otherMessageAppOld.setModeId(otherMessageApp.getModeId());
		otherMessageAppOld.setStatusMsg(MessageStatus.WEI_TUI_SONG.getCode());
		otherMessageAppOld.setTypeMsgEvent(otherMessageApp.getTypeMsgEvent());
		otherMessageAppOld.setTypeMsg(otherMessageApp.getTypeMsg());
		otherMessageAppMapper.deletedRefined(otherMessageAppOld);
		
		//必须项目：站内信 数据状态：@link MessageStatus.WEI_TUI_SONG
		otherMessageApp.initInsertData(userId, creatorName);
		otherMessageApp.setMsgId(msgId);
		otherMessageAppMapper.insert(otherMessageApp);
		//TODO:推送消息到移动端:判断是否推送，如果已推送，已查看则不需要推送；未推送，推送失败需要推送
	}

	/* 
	* @author zhangpp
	* <p>Title: faSongDuanXin</p> 
	* <p>Description: </p> 
	* @param mobile
	* @param code
	* @throws Exception 
	* @see com.zjdiepu.www.ibiz.zpp.AppNewsService#faSongDuanXin(java.lang.String, java.lang.String) 
	* @version V1.0
	*/
	@Override
	public int diepuFaSongDuanXin(String mobile, String code,String message)
	{
		
		try 
		{
			String result = CommonApiUtil.messageUtil(mobile, code,message);
			ShortMessageResult shortMessageResult = new Gson().fromJson(result, ShortMessageResult.class);
			int error_code = shortMessageResult.getError_code();
			return error_code;
		}
		catch (Exception e) 
		{
			
			logger.error(e.getMessage());
		}
		return 0;
	}

	/*  
	*  @author  zhangpp
	*  <p>Title:  jpushHandle</p>  
	*  <p>Description:  </p>  
	*  @param currentUser
	*  @param jpushExt
	*  @throws Exception  
	*  @see com.zjdiepu.www.ibiz.zpp.AppNewsService#jpushHandle(com.zjdiepu.www.base.core.AbstractSysUser, com.zjdiepu.www.model.zpp.pub.ext.JpushExt)  
	*  @version  V1.0
	*/
	@Override
	public void diepuJpushHandle(AbstractSysUser currentUser, JpushExt jpushExt)throws Exception 
	{
		
		//String loginName = currentUser.getName();
		//String loginId = currentUser.getId();
		
		String registrationId = jpushExt.getRegistrationId();
		String alias = jpushExt.getAlias();
		String alert = jpushExt.getAlert();
		String title = jpushExt.getTitle();
		String phoneType = jpushExt.getPhoneType();
		
		if(phoneType.equals("1"))
		{
			JPushClient client = new JPushClient(PayloadBuild.appKeyIos, PayloadBuild.masterSecretIos);
			
			if(null == registrationId || ("").equals(registrationId))
			{
				PushPayload payload = PayloadBuild.buildAndroidWinphonePayload("",alias,title,alert);
				PushResult result = client.sendPush(payload);
				if(result.getResponseCode() != 200)
				{
					throw new BaseException(ResultFlagType.FAIL.toString(),"ANDORID 推送失败！" + result.getOriginalContent());
				}
				return;
			}
			
			PushPayload payload = PayloadBuild.buildAndroidWinphonePayload(registrationId,"",title,alert);
			PushResult result = client.sendPush(payload);
			if(result.getResponseCode() != 200)
			{
				throw new BaseException(ResultFlagType.FAIL.toString(),"ANDORID 推送失败！" + result.getOriginalContent());
			}
			return;
		}
		
		
		JPushClient client = new JPushClient(PayloadBuild.appKeyIos, PayloadBuild.masterSecretIos);
		
		if(null == registrationId || ("").equals(registrationId))
		{
			PushPayload payload = PayloadBuild.buildIOSPayload("",alias,alert);
			PushResult result = client.sendPush(payload);
			if(result.getResponseCode() != 200)
			{
				throw new BaseException(ResultFlagType.FAIL.toString(),"IOS 推送失败！" + result.getOriginalContent());
			}
			return;
		}
		
		PushPayload payload = PayloadBuild.buildIOSPayload(registrationId,"",alert);
		PushResult result = client.sendPush(payload);
		if(result.getResponseCode() != 200)
		{
			throw new BaseException(ResultFlagType.FAIL.toString(),"IOS 推送失败！" + result.getOriginalContent());
		}
	}

	/*  
	*  @author  zhangpp
	*  <p>Title:  diepuFaSongDuanXin1</p>  
	*  <p>Description:  </p>  
	*  @param mobile
	*  @param code
	*  @param message
	*  @throws Exception  
	*  @see com.zjdiepu.www.ibiz.zpp.AppNewsService#diepuFaSongDuanXin1(java.lang.String, java.lang.String, java.lang.String)  
	*  @version  V1.0
	*/
	@Override
	public void diepuFaSongDuanXin1(String mobile, String code, String message)
			throws Exception {
		
		
		String result = CommonApiUtil.messageUtil(mobile, code,message);
		ShortMessageResult shortMessageResult = new Gson().fromJson(result, ShortMessageResult.class);
		
		int error_code = shortMessageResult.getError_code();
		
		if(error_code == 205401)
		{
			throw new BaseException("205401","错误的手机号码");
		}
		if(error_code == 205402)
		{
			throw new BaseException("205402","错误的短信模板ID");
		}
		if(error_code == 205403)
		{
			throw new BaseException("205403","网络错误,请重试");
		}
		if(error_code == 205404)
		{
			throw new BaseException("205404","发送失败，具体原因请参考返回reason");
		}
		if(error_code == 205405)
		{
			throw new BaseException("205405","号码异常/同一号码发送次数过于频繁");
		}
		if(error_code == 205405)
		{
			throw new BaseException("205405","不被支持的模板");
		}
		if(error_code == 10001)
		{
			throw new BaseException("10001","错误的请求KEY");
		}
		if(error_code == 10002)
		{
			throw new BaseException("10002","该KEY无请求权限");
		}
		if(error_code == 10003)
		{
			throw new BaseException("10003","KEY过期");
		}
		if(error_code == 10004)
		{
			throw new BaseException("10004","错误的OPENID");
		}
		if(error_code == 10005)
		{
			throw new BaseException("10005","应用未审核超时，请提交认证");
		}
		if(error_code == 10007)
		{
			throw new BaseException("10007","未知的请求源");
		}
		if(error_code == 10008)
		{
			throw new BaseException("10008","被禁止的IP");
		}
		if(error_code == 10009)
		{
			throw new BaseException("10009","被禁止的KEY");
		}
		if(error_code == 10011)
		{
			throw new BaseException("10011","当前IP请求超过限制");
		}
		if(error_code == 10012)
		{
			throw new BaseException("10012","请求超过次数限制");
		}
		if(error_code == 10013)
		{
			throw new BaseException("10013","测试KEY超过请求限制");
		}
		if(error_code == 10014)
		{
			throw new BaseException("10014","系统内部异常(调用充值类业务时，请务必联系客服或通过订单查询接口检测订单，避免造成损失)");
		}
		if(error_code == 10020)
		{
			throw new BaseException("10020","接口维护");
		}
		if(error_code == 10021)
		{
			throw new BaseException("10021","接口停用");
		}
	}
}
